const path = require("path"); //导入文件路径模块
const express = require("express"); //导入express框架
const bodyParser = require("body-parser"); //引入解析表单请求参数模块
const cors = require("cors"); //导入跨域模块
const globalError = require("@/middleware/globalError"); //导入全局错误处理中间件
const loggerMiddleware = require("@/middleware/loggerMiddleware"); //导入日志处理中间件
const router = require("@/router"); //导入文件路由中间件
const spaceRouter = require("@/router/space");
//导入文件服务
const FileService = require("@/service/FileService");
const FileController = require("@/controller/FileController");
const useMiddleware = (app) => {
  app
    .use(bodyParser.urlencoded({ extended: false }))
    .use(bodyParser.json())
    .use(cors())
    .use(
      "/public", //只控制拦截这个路径下的静态文件访问
      (req, res, next) => {
        // console.log(req.path);
        //req.path时http://pulic/123456/9.png这样的地址，123456时空间id,9是不带后缀的文件名
        //需要获取文件名和空间id
        const pathArr = req.path.split("/"); //将路径分割成数组
        const fileName = pathArr.at(-1); //获取文件名
        const spaceId = pathArr.at(-2); //获取空间id
        if (fileName && spaceId) {
          FileService.getFileStatus(fileName, spaceId)
            .then((result) => {
              // console.log(result);
              if (result.length > 0 && result[0].status == 0) {
                res.status(404).send("文件已被管理员设置暂停访问");
              } else {
                next();
              }
            })
            .catch((err) => {
              res.status(404).send("文件控制异常，请联系管理员");
            });
        } else {
          next();
        }
      },
      express.static(path.resolve("file_storage"))
    )
    .use(loggerMiddleware)
    .use(router)
    .use(spaceRouter)
    .use(globalError);
};
module.exports = useMiddleware;
